    <?php
	$PRINT_DEBUG = false;
	
	$illustrations_json_key = "illustrations";
	
	//check this: http://www.helloandroid.com/tutorials/connecting-mysql-database
	$dbconn = pg_connect("host=gegevensbanken.khleuven.be port=51314 dbname=lector user=u0055909 password=Z1malwc9");
	
	$result = pg_query($dbconn, "SELECT * FROM mondzorgapp.definitions");
	$numrows = pg_numrows($result);
	
   // Loop on rows in the result set.
   for($ri = 0; $ri < $numrows; $ri++) {
		$row = pg_fetch_array($result, $ri);
		$output[]=$row;
   }
   
   $result = pg_query($dbconn, "SELECT el.id_entry as entryid, i.* FROM mondzorgapp.entry_illustrations as el LEFT JOIN mondzorgapp.illustrations as i ON (id_illustration=el.id_entry)");
   $numrows = pg_numrows($result);

    // Loop on rows in the result set.
   for($ri = 0; $ri < $numrows; $ri++) {
		$row = pg_fetch_array($result, $ri);
		$output = addIllustration($row['entryid'], $output, $row);
   }
   
   // TODO Check encoding cariës stuff..
   print(json_encode($output));
	
   // TODO make chacheing possible
	pg_close($dbconn);	
	
	
	/**
	*	Adds the illustration <illustration> to the array '$illustrations_json_key' in the entrie <entryId> in <allEntries> 
	*
	*	TODO op dit moment verwacht hij dat elke entry minstens 1 illustratie nodig heeft
	*	TODO resultaat van de 2e blob in de browser is zo vreemd - alle informatie verdwijnt terug
	*/
	function addIllustration($entryId, $allEntries, $illustration) {
		global $illustrations_json_key;
		
		$size = sizeof($allEntries);
		
		for($ri = 0; $ri < $size; $ri++) {
			if($allEntries[$ri]['id'] == $entryId) {
				// first illustration in array?
				$illustrations_array = $allEntries[$ri][$illustrations_json_key];
				if( $illustrations_array == null) {
					$illustrations_array = array();
					$allEntries[$ri][$illustrations_json_key] = $illustrations_array;
				}
				$illustrations_array[] = $illustration;
				if($PRINT_DEBUG) print("Adding illustration to entry: " .$entryId . " ; " . $allEntries[$ri]['id'] . "<br />");
				$allEntries[$ri][$illustrations_json_key] = $illustrations_array;
			}
	   }
	   
	   return $allEntries;
	}
?>
